<!--
 * @Author: 冯向博
 * @Date: 2021-10-29 13:10:58
 * @LastEditTime: 2021-10-29 14:51:02
-->
<template>
	<u-upload
		ref="upload"
		:action="action"
		:max-size="5 * 1024 * 1024"
		max-count="1"
		:multiple="false"
		:before-upload="beforeUpload"
		:custom-btn="true"
		:show-progress="false"
		:deletable="false"
		:form-data="formData"
		:show-upload-list="true"
		width="0"
		height="0"
		@on-success="onSuccess"
	>
		<u-avatar
			slot="addBtn"
			:src="vuex_user.avatar_url"
			size="140"
		></u-avatar>
	</u-upload>
</template>

<script>
import loginVue from "../../pages/auth/login.vue";
let _this = {};
export default {
	name: "oss-upload",
	data() {
		return {
			action: "http://www.example.com/upload",
			formData: {},
			upFileName: "",
		};
	},
	created() {
		_this = this;
	},
	methods: {
		/**
		 * 上传前的钩子函数
		 * 注意在小程序中 this 会丢失 需要在 create 组件中重新换算一下 _this = this
		 */
		async beforeUpload(index, list) {
			const { file } = list[0];
			// #ifdef H5
			const fileName = file.name;
			// #endif

			// #ifndef H5
			const fileName = file.path;
			// #endif

			console.log(fileName);
			// 请求 Api 获取 oss token
			const ossToken = await _this.$u.api.authOssToken();
			// console.log(ossToken);

			// 设置上传域名
			_this.action = ossToken.host;

			// 处理唯一文件名
			const suffix = fileName.slice(fileName.lastIndexOf("."));

			const upFileName = _this.$u.guid(20) + suffix;

			_this.upFileName = upFileName;

			console.log(upFileName);
			// 额外的上传参数
			_this.formData = {
				key: upFileName,
				policy: ossToken.policy,
				OSSAccessKeyId: ossToken.accessid,
				success_action_status: "200",
				signature: ossToken.signature,
			};
			return true;
		},
		/***
		 * 上传成功之后的函数
		 */
		async onSuccess() {
			// 移除预览区域的图片
			this.$refs.upload.remove(0);

			// 请求 API 更新头像
			await this.$u.api.userAvatar({ avatar: this.upFileName });
			// 更新缓存用户信息
			this.$u.utils.updateUser();

			this.$u.toast("更新成功");
		},
	},

	components: {},
};
</script>

<style scoped lang="scss"></style>
